package com.heba.view;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.heba.Debug;
import com.heba.bean.diary.ItemImageTagObject;
import com.heba.bean.diary.ItemUploadPhotoObject;
import com.heba.greenmulu.R;
import com.heba.utils.ViewUtils;

import java.io.File;
import java.util.List;

/**
 *
 * @author jason
 */
public class DiaryImageTagLayout extends FrameLayout implements View.OnTouchListener {

    private static final String TAG = "DiaryImageTagLayout";

    private FrameLayout layouPoints;

    private ImageView imgBg;

    private Context mContext;

    private View touchView;

    private int touchPosition;

    private List<ItemImageTagObject> imageTagObjects;

    private ImageTagListener listener;

    int touchSlop;

    int startX = 0;
    int startY = 0;
    int startTouchViewLeft = 0;
    int startTouchViewTop = 0;

    public DiaryImageTagLayout(Context context) {
        this(context, null);
    }

    public DiaryImageTagLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DiaryImageTagLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initView(context, attrs);
    }

    /**
     *
     * @param listener
     */
    public void setOnImageClickListener(ImageTagListener listener) {
        this.listener = listener;
    }

    /**
     * initView
     *
     * @param context
     * @param attrs
     */
    private void initView(Context context, AttributeSet attrs) {

        mContext = context;

        touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();

        View imgPointLayout = inflate(context, R.layout.layout_imgview_tag, this);

        imgBg = imgPointLayout.findViewById(R.id.imgBg);
        layouPoints = imgPointLayout.findViewById(R.id.layouPoints);

        layouPoints.setOnTouchListener(this);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    public void setImgBg(int width, int height, ItemUploadPhotoObject object) {

        ViewGroup.LayoutParams lp = imgBg.getLayoutParams();
        lp.width = width;
        lp.height = height;

        imgBg.setLayoutParams(lp);

        ViewGroup.LayoutParams lp1 = layouPoints.getLayoutParams();
        lp1.width = width;
        lp1.height = height;

        layouPoints.setLayoutParams(lp1);

//        Glide.with(mContext).load(imgUrl).asBitmap().into(imgBg);
        Glide.with(mContext).load(new File(object.getPhotoPath())).into(imgBg);

        /**
         *
         */
        imageTagObjects = object.getImageTagObjectList();
        if (imageTagObjects != null) {
            for (int i = 0; i < imageTagObjects.size(); i++) {
                ItemImageTagObject tagObject = imageTagObjects.get(i);
                addItemToScalePosition(width, height, object, tagObject);
            }
        }

//        addPoints(width, height);

    }

    /**
     *
     *
     * @param width  framelayout
     * @param height framelayout
     */
//    private void addPoints(int width, int height) {
//
//        layouPoints.removeAllViews();
//
//        for (int i = 0; i < points.size(); i++) {
//
//            double width_scale = points.get(i).width_scale;
//            double height_scale = points.get(i).height_scale;
//
//            LinearLayout view = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point, this, false);
//            ImageView imageView = (ImageView) view.findViewById(R.id.imgPoint);
//            imageView.setTag(i);
//
//            AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
//            animationDrawable.start();
//
//            LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
//
//            layoutParams.leftMargin = (int) (width * width_scale);
//            layoutParams.topMargin = (int) (height * height_scale);
//
//            imageView.setOnClickListener(this);
//
//            layouPoints.addView(view, layoutParams);
//        }
//    }

    /**
     *
     * @param width
     * @param height
     * @param uploadPhotoObject
     * @param tagObject
     */
    private void addItemToScalePosition(int width, int height, ItemUploadPhotoObject uploadPhotoObject, ItemImageTagObject tagObject) {

//        layouPoints.removeAllViews();

        float width_scale = (float) tagObject.getX() / width;
        float height_scale = (float) tagObject.getY() / height;

        LinearLayout view = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.layout_img_tag, this, false);
        TextView tv_tag_view = view.findViewById(R.id.tv_tag_view);
        ImageView iv_delete = view.findViewById(R.id.iv_delete);
        tv_tag_view.setText(tagObject.getUserName());

        LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();

        int imgWidth = ViewUtils.getViewHeight(view, false);
        int imgHeight = ViewUtils.getViewHeight(view, true);

        layoutParams.leftMargin = (int) (width * width_scale) - imgWidth / 2;
        layoutParams.topMargin = (int) (height * height_scale) - imgHeight / 2;

        /**
         */
//        tv_tag_view.setOnClickListener(v -> {
//
//        });

        /**
         */
        iv_delete.setOnClickListener(v -> {
            List<ItemImageTagObject> tagObjects = uploadPhotoObject.getImageTagObjectList();
            tagObjects.remove(tagObject);
            layouPoints.removeView(view);
        });

        layouPoints.addView(view, layoutParams);
    }

    /**
     *
     * @param x
     * @param y
     */
    private void addItemPosition(int x, int y, String name) {
//        layouPoints.removeAllViews();

        LinearLayout view = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.layout_img_tag, this, false);
        TextView tv_tag_view = view.findViewById(R.id.tv_tag_view);
        tv_tag_view.setText(name);

        LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();

        int imgWidth = ViewUtils.getViewHeight(tv_tag_view, false);
        int imgHeight = ViewUtils.getViewHeight(tv_tag_view, true);

        layoutParams.leftMargin = x - imgWidth / 2;
        layoutParams.topMargin = y - imgHeight / 2;

        /**
         */
        if (layoutParams.topMargin < 0) {
            layoutParams.topMargin = 0;
        } else if (layoutParams.topMargin > getHeight()) {
            layoutParams.topMargin = getHeight() - imgHeight;
        }

        layouPoints.addView(view, layoutParams);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.d("onTouch ACTION_DOWN", "x = " + event.getX() + ",y = " + event.getY());
                startX = (int) event.getX();
                startY = (int) event.getY();
                if (hasView(startX, startY)) {
                    touchView = layouPoints.getChildAt(touchPosition);
                    startTouchViewLeft = touchView.getLeft();
                    startTouchViewTop = touchView.getTop();
                } else {
                    touchView = null;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d("onTouch ACTION_MOVE", "x = " + event.getX() + ",y = " + event.getY());
                moveView((int) event.getX(),
                        (int) event.getY());
                break;
            case MotionEvent.ACTION_UP:
                Log.d("onTouch ACTION_UP", "x = " + event.getX() + ",y = " + event.getY());
                int endX = (int) event.getX();
                int endY = (int) event.getY();
                if (Math.abs(startX - endX) < touchSlop && Math.abs(startY - endY) < touchSlop) {
//                    if (layouPoints.getChildCount() > 0) {
//                        return true;
//                    }

//                    addItemPosition(endX,endY,"jason");

                    /**
                     */
                    if (listener != null) {
                        /**
                         */
                        listener.onAddTagClick(endX, endY);
                    }
                } else if (touchView != null) {
                    /**
                     *
                     */
                    if (layouPoints.getChildCount() > 0) {
                        //获取移动的view
                        for (int i = 0; i < layouPoints.getChildCount(); i++) {
                            View view = layouPoints.getChildAt(i);
                            int left = view.getLeft() + view.getMeasuredWidth() / 2;
                            int top = view.getTop() + view.getMeasuredHeight() / 2;
                            ItemImageTagObject object = imageTagObjects.get(i);
                            object.setX(left);
                            object.setY(top);
                        }

                        if (listener != null) {
                            listener.onTagConfirmPosition(imageTagObjects);
                            Debug.Log(TAG, "imageTagObjects is " + imageTagObjects.toString());
                        }

//                        View view = layouPoints.getChildAt(touchPosition);
//                        int left = view.getLeft() + view.getMeasuredWidth() / 2;
//                        int top = view.getTop() + view.getMeasuredHeight() / 2;
//                        if (listener != null) {
//                            listener.onTagConfirmPosition(touchPosition, left, top);
//                        }
//                        Debug.Log(TAG, "moveView touchPosition is " + touchPosition + ",view = " + view + ", left = " + left + ",top = " + top);
                    }
                }
                break;
        }
        return true;
    }

    /**
     *
     * @param x
     * @param y
     * @return
     */
    private boolean hasView(int x, int y) {
        for (int index = 0; index < layouPoints.getChildCount(); index++) {
            View view = layouPoints.getChildAt(index);
            int left = view.getLeft();
            int top = view.getTop();
            int right = view.getRight();
            int bottom = view.getBottom();
            Rect rect = new Rect(left, top, right, bottom);
            boolean contains = rect.contains(x, y);
            if (contains) {
//                touchView = view;
                touchPosition = index;
//                touchView.bringToFront();
                return true;
            }
        }
        touchView = null;
        return false;
    }

    /**
     *
     * @param x
     * @param y
     */
    private void moveView(int x, int y) {
        if (touchView == null) return;
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params.leftMargin = x - startX + startTouchViewLeft;
        params.topMargin = y - startY + startTouchViewTop;
        if (params.leftMargin < 0 || (params.leftMargin + touchView.getWidth()) > getWidth())
            params.leftMargin = touchView.getLeft();
        if (params.topMargin < 0 || (params.topMargin + touchView.getHeight()) > getHeight())
            params.topMargin = touchView.getTop();
        touchView.setLayoutParams(params);
    }

    /**
     * ImageTagListener
     */
    public interface ImageTagListener {

        void onAddTagClick(int x, int y);

        void onTagConfirmPosition(List<ItemImageTagObject> list);

    }
}
